package com.hjw.controller;


import com.hjw.constants.MessageConstant;
import com.hjw.util.AliOssUtil;
import com.hjw.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    /**
     * 文件上传
     * @param file
     * @return
     */
    @Autowired
    private AliOssUtil aliOssUtil;
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info("文件上传... {}",file);
        //获取原始文件名
        final String originalFilename = file.getOriginalFilename();
        final String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //文件上传
        String filename = UUID.randomUUID().toString() + extension;
        try {
            String filePath = aliOssUtil.upload(file.getBytes(), filename);
            return R.ok(filePath);
        }catch (IOException ex){
            log.error(ex.getMessage());
        }
        return R.fail(MessageConstant.UPLOAD_FAILED);
    }

}
